
package uk.ac.cam.cl.oscar.MMS_server;

import java.net.Socket;
import java.awt.image.BufferedImage;
import java.util.*;

import uk.ac.cam.cl.oscar.*;
import uk.ac.cam.cl.oscar.sift.*;

public class RequestProcessor implements Runnable{
    
    private Socket s;
    private BufferedImage image;
    private ImageRecord[] matches;
    private String tariffNoMMSSent = "12";
    private String tariffMMSSent= "12";
    
    private Demonstration DemoAppInst;
    
    RequestProcessor(Socket sock){
        this.s = sock;        
    }
    
    public void run(){
        
        /*Instantiate Image Downloader class*/
        ImageDownloader imageDownloader = new ImageDownloader();
        /*Receive HTTP post from gateway and extract image location from it*/
        imageDownloader.getMMSImageLocation(s);
        System.out.printf("%s%n", imageDownloader.url);
        /*check if image present. If present download it, 
        otherwise send error message by SMS to user*/
        if(!imageDownloader.imagePresent){
            String str = "No+Image+was+sent+by+MMS,+please+try+again";
            SendPremiumSMS.send(str, imageDownloader.phoneNo, imageDownloader.network, tariffNoMMSSent);
            return;
        }
        else{
            this.image = imageDownloader.downloadImage();
        }
        System.out.printf("Image Downloaded");
        
        // tell the demo applet that there's a new request
        if(Demonstration.DemoAppInst != null){
            Demonstration.DemoAppInst.processNewRequest(this);
            Demonstration.DemoAppInst.displayNewInitImage(this.toString(), image);
        }
        
        /*Process image, query database and return relevant matches*/
        Vector<ImageRecord> vm = ImageFinder.getMatches(image);
        matches = new ImageRecord[vm.size()];
        ListIterator li = vm.listIterator();
        int i = 0;
        while(li.hasNext()){
            matches[i] = (ImageRecord)li.next();
            i++;
        }
        System.out.printf("its a miracle");
        /*Instantiate SendMMS class*/
        SendMMS sendMMS = new SendMMS();
        /*Create new MMS using return details*/
        sendMMS.compileMMS(matches);
        /*Send MMS back to user with results*/
        sendMMS.send(imageDownloader.phoneNo);
      
        /*Send premium rate SMS to recover cost of MMS message*/
        String chargeResponse = String.format("You+have+been+charged+%sp+for+using+this+system", tariffMMSSent);
        SendPremiumSMS.send(chargeResponse, imageDownloader.phoneNo, imageDownloader.network, tariffMMSSent);
    }
   
        
 }


